<script setup>
import HeadComponents from "@/components/headComponents.vue";
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "@/utils/http";

// 病史记录
const medicalHistory = ref([]);
const loading = ref(false);
const diseaseQuery = ref("");

// 从后端加载病史记录
const loadMedicalHistory = async () => {
  loading.value = true;
  try {
    const response = await http.get('/medical-history/');
    medicalHistory.value = response.data;
  } catch (error) {
    console.error('加载病史记录失败:', error);
    ElMessage.error('加载病史记录失败');
  } finally {
    loading.value = false;
  }
};

// 查询疾病信息（已移至navigationPage实现）
const queryDisease = async () => {
  if (!diseaseQuery.value.trim()) {
    ElMessage.warning('请输入疾病名称');
    return;
  }

  loading.value = true;
  try {
    // 直接从后端加载病史记录（疾病查询功能已移至navigationPage）
    await loadMedicalHistory();
    ElMessage.info('病史记录已刷新');
    // 清空输入框
    diseaseQuery.value = "";
  } catch (error) {
    console.error('刷新病史记录失败:', error);
    ElMessage.error('刷新病史记录失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 删除病史记录
const deleteMedicalHistory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条病史记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    await http.delete(`/medical-history/${id}`);
    ElMessage.success('病史记录已删除');
    // 重新加载病史记录
    await loadMedicalHistory();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除病史记录失败:', error);
      ElMessage.error('删除病史记录失败');
    }
  }
};

// 编辑病史记录
const editMedicalHistory = async (record) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入新的内容', '编辑病史记录', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: record.content,
      inputType: 'textarea',
      inputRows: 6,
    });

    if (value !== null) {
      await http.put(`/medical-history/${record.id}`, {
        title: record.title,
        content: value
      });
      ElMessage.success('病史记录已更新');
      // 重新加载病史记录
      await loadMedicalHistory();
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('编辑病史记录失败:', error);
      ElMessage.error('编辑病史记录失败');
    }
  }
};

// 刷新病史记录
const refreshMedicalHistory = async () => {
  await loadMedicalHistory();
  ElMessage.success('病史记录已刷新');
};

// 搜索过滤
const searchQuery = ref('');
const filteredMedicalHistory = computed(() => {
  if (!searchQuery.value) {
    return medicalHistory.value;
  }
  const query = searchQuery.value.toLowerCase();
  return medicalHistory.value.filter(record =>
    record.title.toLowerCase().includes(query) ||
    record.content.toLowerCase().includes(query)
  );
});

onMounted(() => {
  loadMedicalHistory();
});
</script>

<template>
  <head-components></head-components>
  <div class="container">
    <div class="card">
      <h3>病史记录管理</h3>

      <!-- 疾病查询表单 -->
      <div class="query-section">
        <h4>疾病信息查询</h4>
        <div class="query-form">
          <input
            v-model="diseaseQuery"
            placeholder="请输入疾病名称，如：感冒、高血压等"
            class="form-input"
            @keyup.enter="queryDisease"
          />
          <button class="btn btn-primary" @click="queryDisease" :disabled="loading">
            {{ loading ? '查询中...' : '查询并保存' }}
          </button>
        </div>
        <!-- 流式输出显示区域 -->
        <div id="stream-container" class="stream-container"></div>
      </div>

      <!-- 病史记录列表 -->
      <div class="history-section">
        <div class="history-header-bar">
          <h4>我的病史记录</h4>
          <div class="history-controls">
            <input
              v-model="searchQuery"
              placeholder="搜索病史记录..."
              class="search-input"
            />
            <button class="btn btn-secondary" @click="refreshMedicalHistory" :disabled="loading">
              刷新
            </button>
          </div>
        </div>

        <div v-if="loading && medicalHistory.length === 0" class="loading">加载中...</div>
        <ul class="history-list" v-else-if="filteredMedicalHistory.length">
          <li v-for="record in filteredMedicalHistory" :key="record.id" class="history-item">
            <div class="history-header">
              <h5>{{ record.title }}</h5>
              <span class="history-date">{{ new Date(record.created_at).toLocaleString() }}</span>
            </div>
            <div class="history-content">
              <pre>{{ record.content }}</pre>
            </div>
            <div class="history-actions">
              <button class="btn btn-primary" @click="editMedicalHistory(record)" :disabled="loading">
                编辑
              </button>
              <button class="btn btn-danger" @click="deleteMedicalHistory(record.id)" :disabled="loading">
                删除
              </button>
            </div>
          </li>
        </ul>

        <p v-else-if="!loading">暂无病史记录</p>
      </div>
    </div>
  </div>
</template>

<style>
@import '@/assets/base.css';
.container {
  flex: 1;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  position: relative;
}

.query-section, .history-section {
  margin-bottom: 2rem;
}

.query-form {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.form-input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.history-header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.history-controls {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.search-input {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  width: 200px;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.stream-container {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
}

.stream-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  font-size: 0.95rem;
  line-height: 1.5;
  margin: 0;
}

.history-list {
  list-style-type: none;
  padding-left: 0;
}

.history-item {
  background-color: #f9f9f9;
  border: 1px solid #eee;
  padding: 1rem;
  margin-bottom: 1rem;
  border-radius: 6px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.history-header h5 {
  margin: 0;
  color: #333;
}

.history-date {
  color: #666;
  font-size: 0.9rem;
}

.history-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #fff;
  padding: 1rem;
  border-radius: 4px;
  border: 1px solid #eee;
  font-family: inherit;
  font-size: 0.95rem;
  line-height: 1.5;
  margin: 0;
}

.history-actions {
  margin-top: 1rem;
  text-align: right;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.loading {
  text-align: center;
  padding: 2rem;
  color: #666;
}
</style>